package org.example.buysystem.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.buysystem.common.Result;
import org.example.buysystem.constants.Constants;
import org.example.buysystem.entity.MyFile;
import org.example.buysystem.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/file")
@CrossOrigin
@Api(tags = "文件接口")
public class FileController {

    @Autowired
    private FileService fileService;

    @GetMapping("/{fileName}")
    @ApiOperation(value = "获取文件")
    public void file(@PathVariable String fileName, HttpServletResponse response) {
        fileService.download(fileName, response);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传文件")
    public Result upload(@RequestBody MultipartFile file) {
        String url=fileService.upload(file);
        return Result.success(url);

    }

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result page(@RequestParam(required = false,defaultValue = "1") int pageNum,
                       @RequestParam(required = false,defaultValue = "10") int pageSize,
                       @RequestParam String fileName) {
        IPage<MyFile> myFileIPage=fileService.selectPage(pageNum,pageSize,fileName);
        return Result.success(myFileIPage);
    }

    @PostMapping("/del/batch")
    @ApiOperation("批量删除文件")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        for(Integer id:ids){
            int i=fileService.fakedelete(id);
            if(i!=1){
                return Result.error(Constants.CODE_500,"删除文件"+fileService.getById(id).getName()+"失败，文件已被删除");
            }
        }
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("单个id删除")
    public Result delete(@PathVariable Integer id) {
        int i=fileService.fakedelete(id);
        if(i==1){
            return Result.success();
        }else{
            return Result.error(Constants.CODE_500,"删除文件"+fileService.getById(id).getName()+"失败，文件已被删除");
        }
    }

}
